<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -176px;width: 128%"
              label="店铺">
              <j-dict-select-tag v-decorator="['storeId', validatorRules.storeId]" placeholder="请选择门店"
                                 :triggerChange="true" dictCode="stm_store_info,name,store_id,status!=0"/>
            </a-form-item>
          </a-col>
        </a-row>
        <!--        <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="收支类型">
                  <a-input placeholder="请输入收支类型" v-decorator="['categoryType', {}]" />
                </a-form-item>-->
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="科目大类">
              <j-dict-select-tag v-decorator="['categoryId', validatorRules.categoryId]" placeholder="请选择科目大类"
                                 @change="handleCategoryChange" :triggerChange="true" dictCode="fms_category,name,id,cancel_flag=0"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-right: 20px"
              label="科目小类">
              <a-select placeholder="请选择科目小类" v-decorator="[ 'categorySubId', validatorRules.categorySubId]" :options="categorySubOptions"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="费用金额">
              <a-input-number v-decorator="[ 'amount', validatorRules.amount]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="发生日期">
              <a-date-picker v-decorator="[ 'occurTime', validatorRules.occurTime]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="票据">
              <a-upload
                listType="picture-card"
                class="pic-uploader"
                :showUploadList="false"
                :action="uploadAction"
                :data="{'isup':1,'dir':'fms/feeInput'}"
                :headers="headers"
                :beforeUpload="beforeUpload"
                @change="handleChange"
              >
                <img v-if="picUrl" :src="getPicView()" alt="pic" style="height:104px;max-width:300px"/>
                <div v-else>
                  <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>

            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-right: 20px"
              label="费用发生对象">
              <a-input placeholder="请输入费用发生对象" v-decorator="['name', {}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -176px;width: 128%"
              label="备注">
              <a-textarea :rows="2" placeholder="请输入备注" v-decorator="['note', {}]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import {httpAction, getAction} from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"

export default {
  name: 'FmsFeeInputModal',
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      categorySubOptions: [],
      confirmLoading: false,
      uploadLoading: false,
      picUrl: '',
      form: this.$form.createForm(this),
      validatorRules: {
        storeId: { rules: [{ required: true, message: '请选择门店!' }] },
        categoryId: { rules: [{ required: true, message: '请选择科目大类!' }] },
        categorySubId: { rules: [{ required: true, message: '请选择科目小类!' }] },
        amount: { rules: [{ required: true, message: '费用金额不能为空!' }] },
        occurTime: { rules: [{ required: true, message: '发生日期不能为空!' }] },
      },
      url: {
        fileUpload: window._CONFIG['domianURL']+"/sys/common/ossUpload",
        imgerver: window._CONFIG['domianURL']+"/sys/common/view",
        add: '/fms/fmsFeeInput/add',
        edit: '/fms/fmsFeeInput/edit',
        queryFmsCategorySubByMainId: '/fms/fmsCategory/queryFmsCategorySubByMainId',
      }
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = {"X-Access-Token":token};
  },
  computed:{
    uploadAction:function () {
      return this.url.fileUpload;
    }
  },
  methods: {
    add() {
      this.categorySubOptions = [];
      this.picUrl = ''
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.picUrl = this.model.pics;
      this.visible = true
      if (this.model) {
        this.getCategorySubByMainId(this.model.categoryId);
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'storeId', 'categoryType', 'categoryId', 'categorySubId', 'name', 'amount', 'note', 'position'))
        //时间格式化
        this.form.setFieldsValue({ occurTime: this.model.occurTime ? moment(this.model.occurTime) : null })
      })

    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          //时间格式化
          formData.occurTime = formData.occurTime ? formData.occurTime.format() : null

          console.log(formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    handleCategoryChange (e) {
      //this.categoryMainId = e.toString();
      this.form.setFieldsValue({ categoryId: e , categorySubId: '' });
      this.categorySubOptions = [];
      this.getCategorySubByMainId(e.toString());
    },
    getCategorySubByMainId(mainId){
      getAction(this.url.queryFmsCategorySubByMainId,{mainId:mainId}).then(res=>{
        if(res.success){
          this.categorySubOptions = res.result.map(data => ({ label: data['name'], value: data['id'] }));
        }else{
          console.log(res.message);
        }
      });
    },
    beforeUpload: function(file){
      var fileType = file.type;
      if(fileType.indexOf('image')<0){
        this.$message.warning('请上传图片');
        return false;
      }
      //TODO 验证文件大小
    },
    handleChange (info) {
      this.picUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLoading = true;
        return
      }
      if (info.file.status === 'done') {
        let response = info.file.response;
        this.uploadLoading = false;
        console.log(response);
        if(response.success){
          this.model.pics = response.message;
          this.picUrl = this.model.pics;
        }else{
          this.$message.warning(response.message);
        }
      }
    },
    getPicView(){
      if(this.model.pics !== null && this.model.pics !== undefined && this.model.pics !== ''){
        if('http' === this.model.pics.substring(0,4)){
          return this.model.pics;
        }
        return this.url.imgerver +"/"+ this.model.pics;
      }
    },

  }
}
</script>

<style lang="less" scoped>

</style>